package yaohua.main;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.conn.HttpHostConnectException;

import yaohua.entity.Entity_help;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

/**
 * @author yh 登录界面
 */
public class ZbdxActivity extends Activity
	{

		@Override
		public boolean onOptionsItemSelected(MenuItem item)
			{
				new AlertDialog.Builder(this).setTitle("关于").setMessage("本程序为中北大学图书馆使用,欢迎您能向作者提供在使用过程中的bug,以方便作者进行修改.联系作者新浪微薄@耀华info")
						.show();
				return super.onOptionsItemSelected(item);
			}

		@Override
		public boolean onCreateOptionsMenu(Menu menu)
			{
				menu.add("关于");
				return super.onCreateOptionsMenu(menu);
			}

		/** Called when the activity is first created. */

		ProgressDialog progressDialog;
		public static final String LOGIN = "http://202.207.182.100:8080/pft/dzjs/login.asp";
		public static final String SETTING_INFOS = "SETTINGInfos";
		public static final String NAME = "NAME";
		public static final String PASSWORD = "PASSWORD";
		public static final String ISCHECKED = "ISCHECKED";
		private Button login;
		private Button search;
		private EditText username_main;
		private EditText password_main;
		private CheckBox save_main;

		// ProgressDialog progressDialog;

		@Override
		public void onCreate(Bundle savedInstanceState)
			{
				super.onCreate(savedInstanceState);
				// 设置无标题
				requestWindowFeature(Window.FEATURE_NO_TITLE);
				setContentView(R.layout.main);
				// 取出所有的组件
				login = (Button) findViewById(R.id.login);
				search=(Button)findViewById(R.id.search);
				username_main = (EditText) findViewById(R.id.username1);
				password_main = (EditText) findViewById(R.id.password1);
				save_main = (CheckBox) findViewById(R.id.save);
				// 为登录按钮绑定监听器
				login.setOnClickListener(new LoginListener());
				search.setOnClickListener(new searchListener());
				// 读取保存的用户信息
				readSharedPreferences();
			}

		/**
		 * 保存用户名和密码信息
		 */
		@Override
		protected void onStop()
			{
				super.onStop();
				if (save_main.isChecked())
					{
						// 首先获取一个 SharedPreferences 对象
						SharedPreferences settings = getSharedPreferences(SETTING_INFOS, 0);
						// 将用户名和密码保存进去
						settings.edit().putString(NAME, username_main.getText().toString())
								.putString(PASSWORD, password_main.getText().toString()).commit();
						settings.edit().putBoolean(ISCHECKED, save_main.isChecked());
					}
				else
					{
						// 首先获取一个 SharedPreferences 对象
						SharedPreferences settings = getSharedPreferences(SETTING_INFOS, 0);
						// 没被选中时清除信息和取消选中状态
						settings.edit().putString(NAME, "").putString(PASSWORD, "").commit();
						settings.edit().putBoolean(ISCHECKED, save_main.isChecked());
					}
			}

		/**
		 * 登录代码,显示登录状态
		 * 
		 * @throws IOException
		 * @throws ParseException
		 */
		public void login(String username, String password)
			{
				Entity_help entity_help = new Entity_help();
				HttpResponse httpResponse = entity_help.postResponse(LOGIN, "user", username, "pw", password);
				// 没有网络的话，此处httpResponse==null
				if (httpResponse == null)
					{
						Message msg = new Message();
						msg.arg1 = -1;
						handler.sendMessage(msg);
					}
				// 服务器错误
				if (!entity_help.code200(httpResponse))
					{
						Message msg = new Message();
						msg.arg1 = -2;
						handler.sendMessage(msg);
					}
				else
					{
						// 获得返回的的登录提示文字
						HttpEntity entity = entity_help.getEntity(httpResponse);

						String result = entity_help.getContent(entity);

						Pattern regex = Pattern.compile("欢迎", Pattern.DOTALL | Pattern.MULTILINE | Pattern.UNICODE_CASE);
						Matcher regexMatcher = regex.matcher(result);
						boolean foundMatch = regexMatcher.find();
						if (foundMatch)
							{
								// 提示handler登录成功
								Message msg = new Message();
								msg.arg1 = 1;
								handler.sendMessage(msg);
								// 如果登录成功则实现跳转
								Intent intent = new Intent();
								intent.setClass(ZbdxActivity.this, MyTabActivity.class);
								this.startActivity(intent);

							}
						else
							{
								// 提示handler登录密码错误
								Message msg = new Message();
								msg.arg1 = 0;
								handler.sendMessage(msg);
							}
					}

			}

		/**
		 * 读取用户名和密码信息
		 */

		public void readSharedPreferences()
			{
				// 取一个SharedPreferences对象，SETTING_INFOS与SETTING_INFOS.XML文件相对应
				// 效果相当于读取SETTING_INFOS.XML文件，如果文件不存在，则进行创建
				SharedPreferences settings = getSharedPreferences(SETTING_INFOS, 0);
				// 取出保存的NAME，PASSWORD，取出该字段名的值，不存在则创建默认为空
				String name = settings.getString(NAME, "");// 取出保存的 NAME
				String password = settings.getString(PASSWORD, "");// 取出保存的PASSWORD
				boolean ischecked = settings.getBoolean(ISCHECKED, true);// 取出保存的ISCHECKED
				// set value
				username_main.setText(name);
				password_main.setText(password);
				save_main.setChecked(ischecked);
			}

		/**
		 * handler 异步处理登录进度条
		 */
		Handler handler = new Handler()
			{

				@Override
				public void handleMessage(Message msg)
					{
						super.handleMessage(msg);
						if (msg.arg1 == 0)
							{
								progressDialog.dismiss();
								Toast.makeText(getApplicationContext(), "用户名或密码错误，请重新登录", Toast.LENGTH_SHORT).show();
							}
						else if (msg.arg1 == 1)
							{
								progressDialog.dismiss();
								Toast.makeText(getApplicationContext(), "登录成功", Toast.LENGTH_SHORT).show();
							}
						else if (msg.arg1 == -1)
							{
								progressDialog.dismiss();
								Toast.makeText(getApplicationContext(), "网络连接不可用，请检查网络设置", Toast.LENGTH_SHORT).show();
							}
						else if (msg.arg1 == -2)
							{
								progressDialog.dismiss();
								Toast.makeText(getApplicationContext(), "内部服务器错误", Toast.LENGTH_SHORT).show();
							}
					}

			};

		/**
		 * button监听器，如果登录成功则实现Actity的跳转
		 * 
		 * @author yh
		 * 
		 */
		class LoginListener implements OnClickListener
			{

				private String username_string = "";
				private String passowrd_string = "";

				public void onClick(View v)
					{

						progressDialog = ProgressDialog.show(ZbdxActivity.this, "正在登录", "请稍等...", false, true);
						new Thread(new Runnable()
							{

								public void run()
									{
										username_string = username_main.getText().toString();
										passowrd_string = password_main.getText().toString();

										try
											{
												Looper.prepare();
												login(username_string, passowrd_string);

											}
										catch (Exception e)
											{
												e.printStackTrace();

											}
										finally
											{
												progressDialog.dismiss();
											}

									}

							}).start();

					}
			}
		/**
		 * 跳转到search界面的监听代码
		 * @author yh
		 *
		 */
		class searchListener implements OnClickListener
		{

			public void onClick(View v)
				{
					// TODO Auto-generated method stub
					Intent intent=new Intent();
					intent.setClass(ZbdxActivity.this, SearchActivity.class);
					ZbdxActivity.this.startActivity(intent);
				}
			
		}

		/**
		 * 登录成功便销毁这个Activity
		 */
		@Override
		protected void onDestroy()
			{
				//System.out.println("onDestroy");
				super.onDestroy();
				finish();
			}

		/**
		 * 登录成功便销毁这个Activity
		 */
		@Override
		protected void onPause()
			{
				//System.out.println("onPause");
				super.onPause();
				finish();
			}

	}
